package me.flyray.admin.rest;

import me.flyray.admin.biz.*;
import me.flyray.admin.constant.AdminCommonConstant;
import me.flyray.admin.entity.*;
import me.flyray.admin.vo.AuthorityMenuTree;
import me.flyray.admin.vo.GroupUsers;
import me.flyray.admin.vo.MenuTree;
import me.flyray.admin.vo.UserVo;
import me.flyray.common.msg.BaseApiResponse;
import me.flyray.common.msg.TableResultResponse;
import me.flyray.common.rest.BaseController;
import me.flyray.common.util.SnowFlake;
import me.flyray.common.util.TreeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *　@author bolei
 *　@date Apr 8, 2018
　*　@description 
**/

@RestController
@RequestMapping("role")
public class RoleController extends BaseController<RoleBiz, Role> {
	
	@Autowired
	private RoleBiz roleBiz;
    @Autowired
    private MenuBiz menuBiz;
    @Autowired
    private UserBiz userBiz;
    @Autowired
    private RoleApplicationBiz roleApplicationBiz;
    @Autowired
    private BaseApplicationBiz baseApplicationBiz;

    /**
     * 新增role并分配角色
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public BaseApiResponse addRole(@RequestBody Role role) throws Exception {
        role.setRoleId( String.valueOf(SnowFlake.getId()));
        baseBiz.insertSelective(role);
        List<String> appIds = role.getAppIds();
        RoleApplication del = new RoleApplication();
        del.setRoleId(role.getRoleId());
        roleApplicationBiz.delete(del);
        for (int i = 0; i < appIds.size(); i++) {
            RoleApplication roleApplication = new RoleApplication();
            roleApplication.setAppId(appIds.get(i));
            roleApplication.setRoleId(role.getRoleId());
            roleApplicationBiz.insert(roleApplication);
        }
        return BaseApiResponse.newSuccess();
    }

    /**
     * 更新role并分配角色
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public BaseApiResponse updateRole(@RequestBody Role role) throws Exception {
        baseBiz.updateById(role);
        List<String> appIds = role.getAppIds();
        RoleApplication del = new RoleApplication();
        del.setRoleId(role.getRoleId());
        roleApplicationBiz.delete(del);
        for (int i = 0; i < appIds.size(); i++) {
            RoleApplication roleApplication = new RoleApplication();
            roleApplication.setAppId(appIds.get(i));
            roleApplication.setRoleId(role.getRoleId());
            roleApplicationBiz.insert(roleApplication);
        }
        return BaseApiResponse.newSuccess();
    }
	
	/**
	 * 根据部门查询部门下的角色
	 * @return
	 */
	@RequestMapping(value = "/pageList", method = RequestMethod.GET)
    @ResponseBody
	public TableResultResponse<Role> queryList(@RequestParam Map<String, Object> params){
		params.put("platformId", setPlatformId((String) params.get("platformId")));
		return roleBiz.queryList(params);
	}

    /**
     * 查询角色的授权应用
     * @param param
     * @return
     */
    @RequestMapping(value = "/authority/app", method = RequestMethod.GET)
    @ResponseBody
    public BaseApiResponse<List<BaseApplication>> listUserAuthorityMenu(@RequestParam Map<String, Object> param){
        String roleId = (String)param.get("roleId");
        List<BaseApplication> applications = baseApplicationBiz.selectByRoleId(roleId);
        return BaseApiResponse.newSuccess(applications);
    }

    /**
     * 查询角色的应用授权菜单
     * @param param
     * @return
     */
    @RequestMapping(value = "/app/authority/menu", method = RequestMethod.GET)
    @ResponseBody
    public BaseApiResponse<List<AuthorityMenuTree>> getMenuAuthority(@RequestParam Map<String, Object> param){
        String appId = (String) param.get("appId");
        String roleId = (String) param.get("roleId");
        return BaseApiResponse.newSuccess(menuBiz.getRoleAppAuthorityMenu(roleId,appId));
    }

    /**
     * 查询角色的应用菜单树
     * @param appId
     * @return
     */
    @RequestMapping(value = "/app/authority/menuTree", method = RequestMethod.GET)
    @ResponseBody
    public List<MenuTree> userAuthorityAppMenu(String appId){
        String userId = userBiz.getUserByUsername(getCurrentUserName()).getUserId();
        return getMenuTree(menuBiz.getAuthorityAppMenuByUserIdAppId(userId,appId), AdminCommonConstant.ROOT);
    }

    /**
     * 修改角色权限
     * @param id
     * @param menuTrees
     * @return
     */
    @RequestMapping(value = "/{id}/authority/menu", method = RequestMethod.POST)
    @ResponseBody
    public BaseApiResponse modifyMenuAuthority(@PathVariable  String id, String menuTrees,String appId){
        String [] menus = menuTrees.split(",");
        baseBiz.modifyAuthorityMenu(id,appId, menus);
        return BaseApiResponse.newSuccess();
    }
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<Role> list(String deptId) {
        Example example = new Example(Role.class);
        example.createCriteria().andEqualTo("deptId", deptId);
        return baseBiz.selectByExample(example);
    }
		
    @RequestMapping(value = "/{id}/user", method = RequestMethod.PUT)
    @ResponseBody
    public BaseApiResponse modifiyUsers(@PathVariable int id, String members, String leaders){
        baseBiz.modifyRoleUsers(id, members, leaders);
        return BaseApiResponse.newSuccess();
    }

    @RequestMapping(value = "/{id}/user", method = RequestMethod.GET)
    @ResponseBody
    public BaseApiResponse<GroupUsers> getUsers(@PathVariable int id){
        return BaseApiResponse.newSuccess((GroupUsers)baseBiz.getRoleUsers(id));
    }

    @RequestMapping(value = "/{id}/authority/element/add", method = RequestMethod.POST)
    @ResponseBody
    public BaseApiResponse addElementAuthority(@PathVariable  int id,String appId ,int menuId, int elementId){
        baseBiz.modifyAuthorityElement(id,appId,menuId,elementId);
        return BaseApiResponse.newSuccess();
    }

    @RequestMapping(value = "/{id}/authority/element/remove", method = RequestMethod.POST)
    @ResponseBody
    public BaseApiResponse removeElementAuthority(@PathVariable int id,int menuId, int elementId){
        baseBiz.removeAuthorityElement(id,menuId,elementId);
        return BaseApiResponse.newSuccess();
    }

    @RequestMapping(value = "/{id}/authority/element", method = RequestMethod.GET)
    @ResponseBody
    public BaseApiResponse<List<Element>> getElementAuthority(@PathVariable  int id,int menuId){
        return BaseApiResponse.newSuccess((List<Element>)baseBiz.getAuthorityMenuElement(id,menuId));
    }

    private List<MenuTree> getMenuTree(List<Menu> menus,int root) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        for (Menu menu : menus) {
            node = new MenuTree();
            BeanUtils.copyProperties(menu, node);
            node.setLabel(menu.getTitle());
            node.setParentId(String.valueOf(menu.getParentId()));
            node.setId(String.valueOf(menu.getId()));
            trees.add(node);
        }
        return TreeUtil.bulid(trees,String.valueOf(root)) ;
    }

}
